var express = require("express");
var app = express();
var morgan = require("morgan");
var fs = require("fs");
var path = require("path");
var _ = require("loadsh");
var dayjs = require("dayjs");
var cookie_parser = require("cookie-parser");

// var zh = require("dayjs/locale/zh-cn");
// dayjs.locale(zh);
var customParseFormat = require("dayjs/plugin/customParseFormat");
dayjs.extend(customParseFormat);
var multiparty = require("multiparty");
app.use("/js", express.static("./public/js"));
var FileStreamRotator = require("file-stream-rotator");
var logDirectory = path.join(__dirname, "log");
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
console.log(this, "sadas");
// create a rotating write stream
var accessLogStream = FileStreamRotator.getStream({
  date_format: "YYYYMMDD",
  filename: path.join(logDirectory, "access-%DATE%.log"),
  frequency: "daily",
  verbose: false,
});
// var accessLogStream = fs.createWriteStream(path.join(__dirname, "access.log"), {
//   flags: "a",
// });
// 自定义token
morgan.token("from", function (req, res) {
  return req.query.from || "-";
});
// 日志格式 short joke
morgan.format("joke", "[joke] :method :url :status :from");
app.use(morgan("combined", { stream: accessLogStream }));
const body = require("body-parser");
app.use("/public", express.static("public"));
app.use(body.json()); //body-parser 解析json格式数据
app.use(cookie_parser());
app.use(
  body.urlencoded({
    //此项必须在 bodyParser.json 下面,为参数编码
    extended: true,
  })
);
app.use("*", function (req, res, next) {
  res.setHeader("Access-Control-Allow-Credentials", "true");
  // res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "*");
  // res.header("Access-Control-Allow-Credentials", true);
  // res.header('X-Powered-By', '123')
  // res.cookie('isVisit', 1, {maxAge: 60 * 1000, httpOnly: true})
  // 浏览器响应如下
  //Set-Cookie: isVisit=1; Max-Age=60; Path=/; Expires=Tue, 11 May 2021 01:42:27 GMT; HttpOnly
  res.header("setcookie", "123");
  res.header("Access-Control-Expose-Headers", "setcookie,X-Powered-By");
  next();
});
app.get("/", function (req, res, next) {
  res.sendFile(path.resolve("./index.html"));
});

app.get("/index1", function (req, res, next) {
  res.sendFile(path.resolve("./index1.html"));
});
app.post("/a", (req, res) => {
  console.log(req.body);
  res.cookie("name", "zhangsan", { maxAge: 900000, httpOnly: true });
  res.json({
    name: req.body.name,
    age: req.body.age,
    time: dayjs(new Date()).format("YYYY-MM-DD hh-mm-ss"),
  });
});
app.get("/b", (req, res) => {
  var mysql = require("mysql");
  var connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "test",
  });

  connection.connect();
  connection.query("SELECT * FROM user", function (error, results, fields) {
    if (error) throw error;
    res.json({
      name: req.query.name,
      age: req.query.age,
      loca: dayjs.locale(),
      obj: dayjs(),
      time: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      ios: new Date().toISOString(),
    });
  });
});
app.get("/img", function (req, res) {
  var filepath = "./3.jpg";
  var bData = fs.readFileSync(filepath);
  var base64Str = bData.toString("base64");
  var datauri = "data:image/png;base64," + base64Str;
  res.json({ url: datauri });
});
var debug = require("debug")("app");
app.post("/upla", (req, res) => {
  // 接收文件上传
  let form = new multiparty.Form({
    uploadDir: "./public", //指定上传的文件路径
  });
  form.parse(req, (err, field, files) => {
    let arr =
      files &&
      files.file.map((x) => {
        // 必须这样写
        fs.rename(x.path, "./public/" + x.originalFilename, () => {
          console.log("改名");
        });
      });
    res.end(
      JSON.stringify({
        ok: 200,
      })
    );
  });
  form.on("field", (name, value) => {
    // name:字段名
    // value:值
    console.log("数据:", name, value);
  });
  //接收文件数据
  form.on("file", (name, file) => {
    console.log("文件:", name, file);
  });
  //表单解析完成
  form.on("close", () => {
    console.log("完成");
  });
});
app.post("/send", async (req, res) => {
  function read() {
    return new Promise((resolve, rejects) => {
      fs.readFile("./public/3.jpg", function (err, data) {
        resolve(data);
        rejects(err);
      });
    });
  }
  let data = await read();
  try {
    res.send(data);
  } catch (error) {
    res.send(500);
  }
});
app.get("/video", async (req, res) => {
  function read() {
    return new Promise((resolve, rejects) => {
      fs.readFile("./movie.mp4", function (err, data) {
        resolve(data);
        rejects(err);
      });
    });
  }
  let data = await read();
  try {
    res.send(data);
  } catch (error) {
    res.send(500);
  }
});
app.post("/cookie", (req, res) => {
  res.json({
    cookie: req.cookies,
  });
});
// 运行 DEBUG=app node 01.js
// 输出：app hello +0ms
debug("hello");
app.listen(3000);

module.exports = app;
